﻿using AnyCAD.Foundation;

namespace Rapid.IO.DXF
{
    public class DxfReader
    {
        public TopoShapeList Shapes = new TopoShapeList();

        GPnt ToPoint(netDxf.Vector3 pt)
        {
            return new GPnt(pt.X, pt.Y, pt.Z);
        }
        GPnt ToPoint(netDxf.Vector2 pt)
        {
            return new GPnt(pt.X, pt.Y, 0);
        }
        Vector3 ToColor(netDxf.AciColor clr)
        {
            return new Vector3(clr.R / 255.0f, clr.G / 255.0f, clr.B / 255.0f);
        }

        double D2R(double degreee)
        {
            return degreee / 180.0 * Math.PI;
        }

        public bool Load(string fileName)
        {
            var dxfVersion = netDxf.DxfDocument.CheckDxfFileVersion(fileName);
            // netDxf is only compatible with AutoCad2000 and higher DXF versions
            if (dxfVersion < netDxf.Header.DxfVersion.AutoCad2000)
                return false;

            var dxfDoc = netDxf.DxfDocument.Load(fileName);

            foreach (var line in dxfDoc.Entities.Lines)
            {
                if (line.StartPoint.Equals(line.EndPoint))
                    continue;

                var shape = SketchBuilder.MakeLine(ToPoint(line.StartPoint), ToPoint(line.EndPoint));
                Shapes.Add(shape);
            }

            foreach (var arc in dxfDoc.Entities.Arcs)
            {
                var shape = SketchBuilder.MakeArcOfCircle(new GCirc(new GAx2(ToPoint(arc.Center), GP.DZ()), arc.Radius),
                    D2R(arc.StartAngle), D2R(arc.EndAngle));
                Shapes.Add(shape);
            }

            foreach (var circle in dxfDoc.Entities.Circles)
            {
                var shape = SketchBuilder.MakeCircle(ToPoint(circle.Center), circle.Radius, GP.DZ());
                Shapes.Add(shape);
            }

            foreach(var item in dxfDoc.Entities.MLines)
            {
                Console.WriteLine(item);
                //var vertices = item.Vertexes
            }

            foreach(var item in dxfDoc.Entities.Polylines2D)
            {
                GPntList pnts = new GPntList();
                foreach(var pt in item.Vertexes)
                {
                    pnts.Add(ToPoint(pt.Position));
                }


                var shape = SketchBuilder.MakePolygon(pnts, item.IsClosed);
                Shapes.Add(shape);
            }

            return Shapes.Count > 0;
        }

        
    }
}